% 峰值数据统计分析脚本
% 读取processed文件夹中的peak_data_xxdps.csv文件，计算指定周期数的峰值统计信息
close all; clear; clc;

% 获取当前文件所在目录
current_dir = fileparts(mfilename('fullpath'));
processed_dir = fullfile(current_dir, 'processed');

% 检查processed文件夹是否存在
if ~exist(processed_dir, 'dir')
    error('processed文件夹不存在: %s', processed_dir);
end

% 让用户输入要统计的周期个数
fprintf('请输入要统计的周期个数（例如：5表示取最后5个周期的峰值数据进行统计）：\n');
num_cycles = input('周期个数: ');

% 验证输入
if isempty(num_cycles) || ~isnumeric(num_cycles) || num_cycles < 1
    error('输入无效，请输入一个大于0的整数');
end

fprintf('正在处理最后%d个周期的峰值数据...\n', num_cycles);

% 查找所有peak_data_xxdps.csv文件
peak_files = dir(fullfile(processed_dir, 'peak_data_*dps.csv'));

if isempty(peak_files)
    error('在processed文件夹中没有找到peak_data_xxdps.csv文件');
end

fprintf('找到 %d 个峰值数据文件\n', length(peak_files));

% 初始化数据结构
all_currents = [];  % 存储所有电流值
all_speeds = [];    % 存储所有速度值
cycle_data = containers.Map('KeyType', 'double', 'ValueType', 'any'); % 存储每个速度的周期数据

% 读取所有峰值数据文件
for i = 1:length(peak_files)
    file_path = fullfile(processed_dir, peak_files(i).name);
    fprintf('读取文件: %s\n', peak_files(i).name);
    
    % 从文件名提取速度值
    filename = peak_files(i).name;
    speed_match = regexp(filename, 'peak_data_(\d+)dps\.csv', 'tokens');
    if ~isempty(speed_match)
        speed = str2double(speed_match{1}{1});
        all_speeds = [all_speeds; speed];
        
        % 读取CSV文件
        data = readtable(file_path);
        
        % 检查必要的列是否存在
        required_cols = {'Current_A', 'Cycle_Number', 'Positive_Peak_Nm', 'Negative_Peak_Nm'};
        missing_cols = setdiff(required_cols, data.Properties.VariableNames);
        if ~isempty(missing_cols)
            fprintf('警告: 文件 %s 缺少必要的列: %s，跳过\n', filename, strjoin(missing_cols, ', '));
            continue;
        end
        
        % 获取该速度下所有电流的最大周期数
        max_cycle = max(data.Cycle_Number);
        if max_cycle >= num_cycles
            % 提取最后num_cycles个周期的数据
            start_cycle = max_cycle - num_cycles + 1;
            cycle_mask = data.Cycle_Number >= start_cycle & data.Cycle_Number <= max_cycle;
            
            if any(cycle_mask)
                cycle_subset = data(cycle_mask, :);
                
                % 存储电流值
                all_currents = [all_currents; cycle_subset.Current_A];
                
                % 存储该速度下的周期数据
                cycle_data(speed) = cycle_subset;
                
                fprintf('  速度 %ddps: 找到 %d 个电流条件的最后%d个周期数据（周期%d-%d）\n', ...
                    speed, length(unique(cycle_subset.Current_A)), num_cycles, start_cycle, max_cycle);
            else
                fprintf('  速度 %ddps: 未找到最后%d个周期数据\n', speed, num_cycles);
            end
        else
            fprintf('  速度 %ddps: 总周期数%d小于要求的%d个周期\n', speed, max_cycle, num_cycles);
        end
    else
        fprintf('警告: 无法从文件名 %s 提取速度值，跳过\n', filename);
    end
end

% 去重并排序
all_currents = unique(all_currents);
all_speeds = unique(all_speeds);
all_currents = sort(all_currents);
all_speeds = sort(all_speeds);

fprintf('\n找到的电流值: %s\n', mat2str(all_currents));
fprintf('找到的速度值: %s\n', mat2str(all_speeds));

% 创建结果矩阵
num_currents = length(all_currents);
num_speeds = length(all_speeds);
result_matrix = zeros(num_currents, 1 + num_speeds * 2); % 电流 + 每个速度的峰值统计（均值和标准差）

% 创建列标题
column_names = {'Current_A'};
for i = 1:num_speeds
    speed = all_speeds(i);
    column_names{end+1} = sprintf('Peak_Mean_%ddps', speed);
    column_names{end+1} = sprintf('Peak_Std_%ddps', speed);
end

% 填充结果矩阵
for i = 1:num_currents
    current = all_currents(i);
    result_matrix(i, 1) = current; % 电流值
    
    col_idx = 2;
    for j = 1:num_speeds
        speed = all_speeds(j);
        
        if isKey(cycle_data, speed)
            speed_data = cycle_data(speed);
            current_mask = speed_data.Current_A == current;
            
            if any(current_mask)
                current_data = speed_data(current_mask, :);
                
                % 将所有峰值（正峰值和负峰值）都取绝对值
                all_peaks_abs = [abs(current_data.Positive_Peak_Nm); abs(current_data.Negative_Peak_Nm)];
                
                % 计算绝对值的均值和标准差
                peak_mean = mean(all_peaks_abs);
                peak_std = std(all_peaks_abs);
                
                result_matrix(i, col_idx) = peak_mean;
                result_matrix(i, col_idx + 1) = peak_std;
            else
                % 如果没有该电流的数据，填充NaN
                result_matrix(i, col_idx:col_idx + 1) = NaN;
            end
        else
            % 如果没有该速度的数据，填充NaN
            result_matrix(i, col_idx:col_idx + 1) = NaN;
        end
        
        col_idx = col_idx + 2;
    end
end

% 创建结果表
result_table = array2table(result_matrix, 'VariableNames', column_names);

% 保存结果
output_filename = sprintf('peak_statistics_last_%d_cycles.csv', num_cycles);
output_filepath = fullfile(processed_dir, output_filename);
writetable(result_table, output_filepath);

fprintf('\n===== 统计完成 =====\n');
fprintf('结果已保存到: %s\n', output_filename);
fprintf('统计了 %d 个电流条件，%d 个速度条件下的最后%d个周期峰值数据\n', ...
    num_currents, num_speeds, num_cycles);
fprintf('注意：所有峰值（正峰值和负峰值）都已取绝对值后计算均值和标准差\n');

% 显示结果摘要
fprintf('\n结果摘要:\n');
disp(result_table); 